package com.fa4j.system.account.task;

import com.fa4j.system.account.model.AccountPassword;
import com.fa4j.system.account.repository.AccountPasswordRepository;
import com.fa4j.system.notice.model.NoticeCreateCmd;
import com.fa4j.system.notice.service.NoticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Component
@RequiredArgsConstructor
public class AccountPasswordTask {

    private static final String NOTICE_MESSAGE = "您的{0}即将过期，请尽快修改密码，过期时间{1}";
    private static final String NOTICE_PATH = "/home/userPwdModify";

    private final AccountPasswordRepository accountPasswordRepository;
    private final NoticeService noticeService;


    /**
     * 密码过期任务
     */
    @Scheduled(cron = "${fa4j.task.system-account-passwordExpireJob.cron}")
    public void passwordExpireJob() {
        int size = 100;
        long minId = 0;
        //提前15天通知
        LocalDate date = LocalDate.now().minusDays(15);
        LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
        while (true) {
            List<AccountPassword> list = accountPasswordRepository.queryByBetweenExpireTime(startTime, endTime, minId, size);
            for (AccountPassword accountPassword : list) {
                String content = MessageFormat.format(NOTICE_MESSAGE, accountPassword.getType().getName(), accountPassword.getExpireTime());
                minId = accountPassword.getId();
                NoticeCreateCmd cmd = new NoticeCreateCmd();
                cmd.setAccountId(accountPassword.getAccountId());
                cmd.setTitle(accountPassword.getType().getName() + "即将过期");
                cmd.setContent(content);
                cmd.setLink(NOTICE_PATH);
                cmd.setOperatorId(0L);
                noticeService.create(cmd);
            }
            if (list.size() < size) {
                break;
            }
        }

    }
}
